package com.citytechinc.cmis.client.service
{
	import com.citytechinc.cmis.client.event.TypesEvent;
	import com.citytechinc.cmis.client.model.Property;
	import com.citytechinc.cmis.client.model.Repository;
	import com.citytechinc.cmis.client.model.Type;
	
	import flash.events.EventDispatcher;
	
	import mx.collections.ArrayCollection;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	public class TypesService extends EventDispatcher
	{
		private namespace app = "http://www.w3.org/2007/app";
		private namespace atom = "http://www.w3.org/2005/Atom";
		private namespace cmis = "http://www.cmis.org/2008/05";
		
		use namespace app;
        use namespace atom;
        use namespace cmis;
        
		private var auth:String;
		
		public function TypesService(auth:String)
		{
			this.auth = auth;
		}
		
		public function getRepositoryTypes(repository:Repository):void 
		{
			getTypes(repository.typesURL);
		}
		
		public function getTypes(url:String):void 
		{
			var service:HTTPService = new HTTPService();

			service.url = url;
			service.resultFormat = "e4x";
			service.addEventListener(ResultEvent.RESULT, setTypes)
			service.headers["Authorization"] = "Basic " + auth;
			
			service.send();
		}
		
		private function setTypes(event:ResultEvent):void 
		{
			var types:ArrayCollection = new ArrayCollection();
			
			for each(var t:XML in event.result.entry) 
			{
				var type:Type = new Type();
				
				type.name = t.title;
					
				for each(var dp:XML in t.documentType.children())
					type.properties.addItem(Property.getProperty(dp));
				
				for each(var fp:XML in t.folderType.children())
					type.properties.addItem(Property.getProperty(fp));
				
				for each(var rp:XML in t.relationshipType.children())
					type.properties.addItem(Property.getProperty(rp));
				
				types.addItem(type);
				
				this.dispatchEvent(new TypesEvent(TypesEvent.TYPES, types));
			}
			
		}

	}
	
}